package com.yupi.springbootinit.es.service;

import com.yupi.springbootinit.utils.EsToBeanUtils;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.elasticsearch.action.search.SearchResponse;
import org.springframework.stereotype.Service;

import java.util.List;
import com.yupi.springbootinit.es.entity.ChatSession;

import javax.annotation.Resource;

@Service
public class ChatSessionService {

    @Resource
    private ChatSessionRepository chatSessionRepository;


    public Integer save(ChatSession chatSession) {
        return chatSessionRepository.insert(chatSession);
    }

    /**
     * 根据关键字和userId查询聊天记录
     *
     * @param keyword 关键字
     * @param userId 用户ID
     * @return 包含关键字的聊天记录列表
     */
    public List<ChatSession> findByKeywordAndUserId(String keyword, String userId) {
        // 构建查询条件
        LambdaEsQueryWrapper<ChatSession> query = new LambdaEsQueryWrapper<>();
        query.matchPhrase(keyword, "messageList");
        query.eq("senderId", userId);
        // 执行查询
        SearchResponse search = chatSessionRepository.search(query);
        // 解析查询结果
        return EsToBeanUtils.parseSearchResponse(search);
    }
    public void createIndex() {
        chatSessionRepository.createIndex();
    }

    public void deleteIndex() {
        chatSessionRepository.deleteIndex("message_index");
    }
}